import { useRequest } from 'ahooks';
import { Button, Card, Icon, Menu, Popconfirm, Popover, Row, Tooltip } from 'antd';
import Search from 'antd/lib/input/Search';
import upperFirst from 'lodash/upperFirst';
import React, { useEffect, useRef, useState } from 'react';
import PubSub from 'pubsub-js';
import request from '@/utils/request';
import useModal from '@/hooks/UseModal';
import IconButton from '../IconButton';
import SearchableTree from '../SearchableTree';
import CatalogEditModal from './components/CatalogEditModal';
import styles from './index.less';

function CatalogPanel({ name, code, height, onAddLeaf, onEditLeaf }) {
  const [value, setValue] = useState('');
  const treeRef = useRef();
  const { showModal, hideModal, visible, data } = useModal();

  const refreshTree = () => treeRef.current.refresh();

  useEffect(() => {
    PubSub.subscribe('refreshTree', refreshTree);
    return () => PubSub.unsubscribe('refreshTree');
  }, []);

  const { run: deleteLeaf, loading: loading1 } = useRequest(
    leafId => request.post(`/${code}/delete${upperFirst(code)}?${code}Id=${leafId}`),
    { manual: true, onSuccess: refreshTree }
  );

  const { run: deleteCatalog, loading: loading2 } = useRequest(
    catalogId => request.post(`/${code}/deleteCatalog?catalogId=${catalogId}`),
    { manual: true, onSuccess: refreshTree }
  );

  const editLeaf = leaf => {
    onEditLeaf(leaf);
  };

  const editCatalog = catalog => {
    showModal(catalog);
  };

  const renderContent = ({ catalogId }) => (
    <div>
      <Row>
        <Button
          type="default"
          className="margin-bottom"
          onClick={e => {
            e.stopPropagation();
            onAddLeaf(catalogId);
          }}
        >
          新增{name}
        </Button>
      </Row>
      <Row>
        <Button
          type="default"
          onClick={e => {
            e.stopPropagation();
            showModal({ parentCatalogId: catalogId });
          }}
        >
          新增子目录
        </Button>
      </Row>
    </div>
  );

  const renderTitle = node => {
    const { title, leaf, children, key } = node;
    const keyword = value || '';
    const index = title.indexOf(keyword);
    const beforeStr = title.substr(0, index);
    const afterStr = title.substr(index + keyword.length);
    const text =
      index > -1 ? (
        <span>
          {beforeStr}
          <span style={{ color: '#f50' }}>{keyword}</span>
          {afterStr}
        </span>
      ) : (
        <span>{node.title}</span>
      );

    const canDelete = leaf || children.length === 0;

    return (
      <span className={styles.tree_node}>
        <span className={styles.tree_node_title}>{text}</span>
        <span className={styles.tree_node_icons}>
          <IconButton
            icon="edit"
            title="编辑"
            onClick={() => (leaf ? editLeaf(node) : editCatalog(node))}
          />
          <Popover
            arrowPointAtCenter
            placement="right"
            content={renderContent(node)}
            trigger="hover"
          >
            <IconButton icon="plus-circle" title="新增" />
          </Popover>
          {canDelete && (
            <Popconfirm
              title={`确定要删除${leaf ? name : '目录'}【${node.title}】吗`}
              onConfirm={() => (leaf ? deleteLeaf(key) : deleteCatalog(key))}
            >
              <IconButton icon="delete" title="删除" />
            </Popconfirm>
          )}
        </span>
      </span>
    );
  };

  const handleSelect = e => {
    const node = e.node.props.dataRef;
    if (!node) {
      PubSub.publish(`${code}_selectCatalog`, { catalogId: '-1' });
      return;
    }
    if (e.selected) {
      if (node.leaf) {
        PubSub.publish(`${code}_selectLeaf`, node);
      } else {
        PubSub.publish(`${code}_selectCatalog`, node);
      }
    } else {
      PubSub.publish(`${code}_unselect`);
    }
  };

  return (
    <Card
      title={`${name}目录`}
      className="cute"
      bodyStyle={{ padding: '16px 16px 0px 16px', height: height - 37, overflowY: 'auto' }}
      style={{ height }}
      extra={
        <>
          <Tooltip className="margin-right" title="刷新目录树">
            <Icon type="sync" className={styles.icon_hover} onClick={refreshTree} />
          </Tooltip>
          <Tooltip title="新增主目录">
            <Icon type="plus-circle" className={styles.icon_hover} onClick={showModal} />
          </Tooltip>
        </>
      }
    >
      <Search className="margin-bottom" placeholder="Search..." onSearch={setValue} />
      <SearchableTree
        loading={loading1 || loading2}
        renderTitle={renderTitle}
        ref={treeRef}
        keyword={value}
        leafName={code}
        onSelect={handleSelect}
      />
      <CatalogEditModal
        visible={visible}
        code={code}
        onOk={() => treeRef.current.refresh()}
        onClose={hideModal}
        data={data}
      />
    </Card>
  );
}

export default CatalogPanel;
